#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import unittest

import ctpp2

class TestCTPP2(unittest.TestCase):

    def setUp(self):
        self.t = ctpp2.CTPP2();
        self.t.include_dirs(('testdata',));

    def test_01(self):
        bytecode = self.t.parse_template('hello.tmpl');
        bytecode.save('hello.ct2');

        bytecode = self.t.load_bytecode('hello.ct2')
        self.t.param({'world' : { 'name' : 'beautiful World' }, 'worldname' : "qweqwe"})
        result = self.t.output(bytecode)
        self.failUnless(result == 'Hello, beautiful World!\n')

        self.t.reset();
        self.failUnless(self.t.dump_params())

        result = self.t.output(bytecode);
        self.failUnless(result == 'Hello, !\n')

        self.t.param({'world' : { 'name' : 'awfull World' }})
        self.failUnless(self.t.dump_params())

        result = self.t.output(bytecode);
        self.failUnless(result == 'Hello, awfull World!\n')

    def test_02(self):
        bytecode = self.t.parse_template('math_expr.tmpl')

        self.t.param({'a': 2, 'b': 3, 'age': 31})

        result = self.t.output(bytecode);
        self.failUnless(result == '  (2 + 3) / 5 = 1\n  Age correct\n')

    def test_03(self):
        self.t.json_param('{ "foo": "bar", "baz" : 123}');
        self.failUnless('{"baz":123,"foo":"bar"}' == self.t.dump_params())

    def test_04(self):
        self.failUnlessRaises(RuntimeError, self.t.parse_template,
                "syntax-error.tmpl")

    def test_05(self):
        bytecode = self.t.parse_template('runtime-error.tmpl')
        self.failUnlessRaises(RuntimeError, self.t.output, bytecode)

    def test_06(self):
        bytecode = self.t.parse_template('hello2.tmpl');
        bytecode.save('hello2.ct2');

        bytecode = self.t.load_bytecode('hello2.ct2')
        self.t.param({'a' : [1, 2, 3], 'b' : [{'k': 'key1', 'v': 'val1'}, {'k': 'key2', 'v': 'val2'}], 'c' : ({'v': 'abc'}, {'v': 'qwe'})})
        result = self.t.output(bytecode)
        self.failUnless(result == 'testing 123\nkey1:val1key2:val2\nabcqwe\nkey2\n')

if __name__ == '__main__':
    unittest.main()

